package com.youdianstar.app.util

import android.content.Context
import androidx.appcompat.app.AppCompatActivity

import com.youdianstar.app.common.STRIPE_KEY
import com.youdianstar.app.common.util.LogUtil
import com.youdianstar.app.common.util.StrUtil

import com.stripe.android.PaymentAuthConfig
import com.stripe.android.PaymentConfiguration
import com.stripe.android.Stripe
import com.stripe.android.googlepaylauncher.GooglePayEnvironment
import com.stripe.android.googlepaylauncher.GooglePayLauncher
import com.stripe.android.googlepaylauncher.GooglePayPaymentMethodLauncher
import java.math.BigDecimal
import java.math.RoundingMode


/**
 * File: StripePaymentEx
 * Author: 82149 Create: 2021/11/24 11:35
 * Changes (from 2021/11/24)
 * --------------------------------------------------
 * description: Stripe 加卡+前端支付+Google支付
 * ---------------------------------------------------
 *
 */

//Stripe初始化
fun initStripe(context: Context): Stripe {
    val uiCustomization = PaymentAuthConfig.Stripe3ds2UiCustomization.Builder()
        .setLabelCustomization(
            PaymentAuthConfig.Stripe3ds2LabelCustomization.Builder()
                .setTextFontSize(12)
                .build()
        )
        .build()

    PaymentAuthConfig.init(
        PaymentAuthConfig.Builder()
            .set3ds2Config(
                PaymentAuthConfig.Stripe3ds2Config.Builder()
                    .setTimeout(5)
                    .setUiCustomization(uiCustomization)
                    .build()
            )
            .build()
    )
    return Stripe(context, PaymentConfiguration.getInstance(context).publishableKey)
}

const val merchantName = "youdianstar"

/**
 * 初始化GooglePayLauncher
 *
 * @param countryCode SG:新加坡 LV:拉脱维亚
 */
fun initGoogleMethodLauncher(mActivity: AppCompatActivity, countryCode:String,
                             readyCallback: GooglePayPaymentMethodLauncher.ReadyCallback,
                             resultCallback: GooglePayPaymentMethodLauncher.ResultCallback
): GooglePayPaymentMethodLauncher {
    PaymentConfiguration.init(mActivity, STRIPE_KEY)
    return GooglePayPaymentMethodLauncher(
        activity = mActivity,
        config = GooglePayPaymentMethodLauncher.Config(
            environment = GooglePayEnvironment.Production,
            merchantCountryCode = countryCode,
            merchantName = merchantName,
//            existingPaymentMethodRequired = false //沙盒模式开启
        ),
        readyCallback = readyCallback,
        resultCallback = resultCallback
    )
}

/**
 * 发起 Google pay
 * --后端下单
 * @param clientSecret 服务端下单获取的secret
 */
fun GooglePayLauncher.startGooglePayment(clientSecret:String,loadingAction:()->Unit){
    loadingAction()
    this.presentForPaymentIntent(clientSecret)
}

/**
 * 发起 Google pay
 * ---前端下单
 * @param currency 货币代码
 * @param amount 支付金额 单位分
 */
fun GooglePayPaymentMethodLauncher.startGooglePayment(currency:String,amount:Int,loadingAction:()->Unit){
    loadingAction()
    this.present(currencyCode = currency, amount = amount)
}


fun onPaymentLauncherResult(result: GooglePayLauncher.Result,
                            onPaySuccess: (String) -> Unit, onPayError: (String?) -> Unit){
    when (result) {
        is GooglePayLauncher.Result.Completed -> {
            onPaySuccess.invoke("")
        }
        GooglePayLauncher.Result.Canceled -> {
            onPayError.invoke("The transaction was canceled by the user.")
        }
        is GooglePayLauncher.Result.Failed -> {
            try {
                onPayError.invoke(result.error.message)
            }catch (e:Exception){
                e.printStackTrace()
            }
        }
    }
}

fun onPaymentMethodResult(result: GooglePayPaymentMethodLauncher.Result,
                       onPaySuccess: (String) -> Unit, onPayError: (String?) -> Unit) {
    when (result) {
        is GooglePayPaymentMethodLauncher.Result.Completed -> {
            val paymentMethodId :String = result.paymentMethod.id?:""
            //LogUtil.d("---Google success = "+paymentMethodId.toString())
            if (StrUtil.isEmpty(paymentMethodId)){
                onPayError.invoke("")
            } else
                onPaySuccess.invoke(paymentMethodId)
        }
        is GooglePayPaymentMethodLauncher.Result.Canceled -> {
            onPayError.invoke("AT-canceled")
        }
        is GooglePayPaymentMethodLauncher.Result.Failed -> {
            try {
                LogUtil.d("---Google error = "+result.error.message)
                onPayError.invoke(result.error.message)
            }catch (e:Exception){
                e.printStackTrace()
            }
        }
    }
}


val microsDecimal = BigDecimal(1000000.0)

/**
 * 转换支付金额单位 元to分
 *
 * @param price 单位 元
 */
fun priceToMicros(price : Double):Int{
    return BigDecimal(price).divide(microsDecimal).setScale(2, RoundingMode.HALF_EVEN).toInt()
}

